package com.vivo.tasks;

import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.vivo.Utils.DingConfUtil;
import com.vivo.Utils.SendDingDingMsgUtil;
import com.vivo.dingtalk.entity.DingOaNotify;
import com.vivo.dingtalk.entity.DingUserInfo;
import com.vivo.dingtalk.service.DingOaNotifyService;
import com.vivo.dingtalk.service.DingUserInfoService;
import com.vivo.dingtalk.web.vm.LinkMsgVM;
import com.vivo.system.entity.VivoDingConf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class TaskDingOaNotify {

    @Autowired
    private DingOaNotifyService oaNotifyService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private DingUserInfoService dingUserInfoService;

    @Autowired
    private DingConfUtil dingConfUtil;

    /**
     * 同步消息
     */
    public void SyncData() {
        NotifyNewMsg();

        // 第二次推送数据
        NotifyReNotifyMsg();
    }


    /**
     * 发送所有新消息， 新消息定义是，status字段状态为： 待发送
     */
    public void NotifyNewMsg() {
        DingOaNotify query = new DingOaNotify();
        query.setStatus("待发送");
        List<DingOaNotify> notifyList = oaNotifyService.findList(query);

        Date dateNow = new Date();

        for (DingOaNotify notify : notifyList) {
            // 发送通知消息

            boolean retFlag = sendOaMsg(notify);

            if (retFlag) {
                notify.setStatus("已发送");
                notify.setFirstNotifyTime(dateNow);
                notify.setLastNotifyTime(dateNow);

                oaNotifyService.save(notify);
            }
        }

        System.out.println("OA新消息发送完毕！");
    }


    /**
     * 发送重复通知， 条件如下：
     * 1. 消息未持续通知2天
     * 2. 消息满足当前时间与最后一条发送时间大于3小时
     * 3. 消息状态为未发送
     */
    public void NotifyReNotifyMsg() {
        DingOaNotify query = new DingOaNotify();
        query.setStatus("已发送");
        List<DingOaNotify> notifyList = oaNotifyService.findList(query);

        Date nowDate = new Date();
        Long nowTsp = nowDate.getTime();
        Calendar cal = Calendar.getInstance();
        cal.setTime(nowDate);

        int curDay = cal.get(Calendar.DAY_OF_YEAR);
        int curHour = cal.get(Calendar.HOUR_OF_DAY);
        int curMin = cal.get(Calendar.MINUTE);
        int minTimeOut = 4 * 60 * 60 * 1000; // 默认提醒间隔不低于4小时

        int msgMinTimeout = 24 * 60 * 60 * 1000; // 默认提醒时间为2天

        for (DingOaNotify notify : notifyList) {
            int notifyHour1 = notify.getNotifyHour1() == null ? 10 : notify.getNotifyHour1();
            int notifyHour2 = notify.getNotifyHour2() == null ? 15 : notify.getNotifyHour2();

            int notifyMin1 = notify.getNotifyMin1() == null ? 30 : notify.getNotifyMin1();
            int notifyMin2 = notify.getNotifyMin2() == null ? 30 : notify.getNotifyMin2();

            // 发送通知消息
            Date lastSendTime = notify.getLastNotifyTime();
            Date firstSendTime = notify.getFirstNotifyTime();
            Long curTsp = lastSendTime.getTime();
            if ((curTsp - nowTsp) < minTimeOut) {
                continue;
            }

            Long firstSendTsp = firstSendTime.getTime();
            if ((nowTsp - firstSendTsp) > msgMinTimeout) {
                notify.setStatus("任务提醒超时");
                oaNotifyService.save(notify);
                continue;
            }

            // 如果小时数 符合发送数据
            if ((curHour == notifyHour1 && (curMin - notifyMin1) < 5) ||
                    (curHour == notifyHour2 && (curMin - notifyMin2) < 5)) {
                sendOaMsg(notify);
                notify.setLastNotifyTime(nowDate);
                oaNotifyService.save(notify);
            }
        }

        System.out.println("重复提醒成功");
    }


    private boolean sendOaMsg(DingOaNotify notify){
        boolean retFlag = false;
        do {
            User user = null;
            if (!StringUtils.isBlank(notify.getEmpId())) {
                user = systemService.getUserByEmpId(notify.getEmpId());
            } else {
                continue;
            }

            if (user == null) {
                System.out.println("找不到对应的用户信息！");
                continue;
            }

            notify.setCompId(user.getCompany().getId());
            notify.setUser(user);

            LinkMsgVM linkMsg = new LinkMsgVM();
            linkMsg.setContent(notify.getContent());
            linkMsg.setPhone(user.getPhone());
            linkMsg.setTitle(notify.getTitle());

            // TODO  拼接url
            try {
                String url = "http://vivo.jsbstx.com/WebReport/ReportServer?formlet=" +
                        URLEncoder.encode(notify.getUrl().trim(), "UTF-8") + "&p99=" + user.getLoginName() + "&op=h5";
                linkMsg.setUrl(url);
            } catch (Exception e) {
                e.printStackTrace();
            }


            DingUserInfo dingUserInfo = dingUserInfoService.getByMobile(user.getLoginName());
            if (dingUserInfo == null) {
                System.out.println("找不到对应的用户钉钉登陆信息！请提醒其进行钉钉登陆操作！");
                continue;
            }
            notify.setDingUserId(dingUserInfo.getDingUserId());

            linkMsg.setDingUserId(dingUserInfo.getDingUserId());

            VivoDingConf dingConf = dingConfUtil.getDingConf(user.getCompany().getId());
            if (dingConf == null) {
                System.out.println("该二级区域还没有进行钉钉绑定设置，提醒管理员进行相关绑定操作！二级区域："
                        + user.getCompany().getName());
                continue;
            }
            linkMsg.setAccessToken(dingConf.getAccessToken());
            linkMsg.setAgentId(Long.parseLong(dingConf.getAgentId()));

            OapiMessageCorpconversationAsyncsendV2Response rsp = null;
            try {
                rsp = SendDingDingMsgUtil.sendWorkMsg(linkMsg);
                System.out.println("钉钉链接消息发送成功！");
                retFlag = true;
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("消息发送失败" + e.getMessage());
            }
        } while (false);

        return retFlag;
    }
}
